export default {
  namespaced:true,
  state:()=>({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下6个属性:
    // { goods_id, goods_name， goods_price, goods_count, goods_small_logo，goods_state }
    cart:JSON.parse(uni.getStorageSync('cart')||'[]')
  }),
  mutations:{
    // 向购物车中添加商品
    addToCart(state,goods){
      const result=state.cart.find(x=>x.goods_id===goods.goods_id)
      if(!result){
        state.cart.push(goods)
      }else{
        result.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    // 保存购物车数据到本地存储
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    // 更新购物车中商品选中状态
    updateGoodsState(state,goods){
      const result=state.cart.find(x=>x.goods_id===goods.goods_id)
      if(result){
        result.goods_state=goods.goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    // 更新购物车中商品的数量
    updateGoodsCount(state,goods){
      const result=state.cart.find(x=>x.goods_id===goods.goods_id)
      if(result){
        result.goods_count=goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    // 移除购物车中的商品
    deleteGoods(state,goods){
      state.cart=state.cart.filter(x=>x.goods_id!==goods.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    // 更新全选状态
    updateFullGoodsState(state,newState){
      state.cart.forEach(x=>x.goods_state=newState)
      this.commit('m_cart/saveToStorage')
    },
    // 清空购物车
    clearCart(state){
      state.cart=[]
      uni.removeStorageSync("cart")
    }
  },
  getters:{
    total(state){
      let a=0
      state.cart.forEach(x=>a+=x.goods_count)
      return a
    },
    chkTotal(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    },
    totalPrice(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
    },
    pickGoodsInfo(state){
      return state.cart.filter(x=>x.goods_state).map(item=>({goods_id:item.goods_id,goods_number:item.goods_count,goods_price:item.goods_price}))
    }
  }
}